<template>
  <div class="visits">
    <div id="visits" style="width: 100%; height: 260px"></div>
  </div>
</template>
<script setup lang="ts">
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
} from "echarts/components";
import { LineChart } from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";

import { onMounted } from "vue";

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
]);

onMounted(() => {
  const chartDom = document.getElementById("visits") as HTMLElement;
  if (chartDom) {
    // 获取 DOM 元素
    if (!chartDom) {
      throw new Error('Element with id "visits" not found');
    }

    // 初始化图表实例
    const myChart = echarts.init(chartDom);

    // 定义数据类型
    interface DataItem {
      name: string;
      value: [string, number];
    }

    function randomData(): DataItem {
      now = new Date(+now + oneDay);
      value = value + Math.random() * 21 - 10;
      return {
        name: now.toString(),
        value: [
          [now.getFullYear(), now.getMonth() + 1, now.getDate()].join("/"),
          Math.round(value),
        ],
      };
    }

    let data: DataItem[] = [];
    let now = new Date(1997, 9, 3);
    const oneDay = 24 * 3600 * 1000;
    let value = Math.random() * 1000;

    for (let i = 0; i < 1000; i++) {
      data.push(randomData());
    }

    // 配置图表选项
    const option: echarts.EChartsCoreOption = {
      title: {
        text: "入站流量",
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params: any[]): string {
          const param = params[0];
          const date = new Date(param.name);
          return `${date.getDate()}/${
            date.getMonth() + 1
          }/${date.getFullYear()} : ${param.value[1]}`;
        },
        axisPointer: {
          animation: false,
        },
      },
      xAxis: {
        type: "time",
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        type: "value",
        boundaryGap: [0, "100%"],
        splitLine: {
          show: false,
        },
      },
      series: [
        {
          name: "Fake Data",
          type: "line",
          showSymbol: false,
          data: data,
        },
      ],
    };

    // 设置初始选项
    myChart.setOption(option);

    // 每秒更新数据
    setInterval(() => {
      for (let i = 0; i < 5; i++) {
        data.shift();
        data.push(randomData());
      }
      myChart.setOption({
        series: [
          {
            data: data,
          },
        ],
      });
    }, 1000);

    window.onresize = () => {
      myChart.resize();
    };
  }
});
</script>
<style lang="scss" scoped></style>
